//
//  UIButton_VC.swift
//  BARXSwiftTest
//
//  Created by 孙博岩 on 2018/7/6.
//  Copyright © 2018 boai. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa


class UIButton_VC: UIViewController {

    private var dispose = DisposeBag()
    let title0 = "博爱温馨提示"
    let msg0 = "欢迎使用 iPhone SE，迄今最高性能的 4 英寸 iPhone。在打造这款手机时，我们在深得人心的 4 英寸设计基础上，从里到外重新构想。它所采用的 A9 芯片，正是在 iPhone 6s 上使用的先进芯片。1200 万像素的摄像头能拍出令人叹为观止的精彩照片和 4K 视频，而 Live Photos 则会让你的照片栩栩如生。这一切，成就了一款外形小巧却异常强大的 iPhone。"
    let buttonTitleArray = ["取消", "确定"]
    
    let timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        setupUI()
        setupTimer()
    }
    
    func setupUI() -> Void {
        
        buttonIsEnabled()
        //        buttonIsSelected()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidLayoutSubviews() {
        
        button.frame = CGRect.init(x: 100, y: 100, width: 200, height: 50)
        button2.frame = CGRect.init(x: 100, y: button.frame.maxY + 20, width: button.frame.width, height: button.frame.height)
        button3.frame = CGRect.init(x: 100, y: button2.frame.maxY + 20, width: button.frame.width, height: button.frame.height)
        
        switch1.frame = CGRect.init(x: 100, y: button3.frame.maxY + 20, width: button.frame.width, height: button.frame.height)
    }
    
    // MARK: - timer
    func setupTimer() -> Void {
        time1()
        time3()
    }
    
    // MARK: 按钮标题（title）的绑定
    func time1() -> Void {
        timer.map{"倒计时\($0)s"}
            .bind(to: button.rx.title(for: .normal))
            .disposed(by: dispose)
    }
    
    // MARK: rx.attributedTitle 为 setAttributedTitle(_:controlState:) 的封装
    func time2() -> Void {
        timer.map(formatTimeInterval)
            .bind(to: button.rx.attributedTitle())
            .disposed(by: dispose)
    }
    
    // MARK: rx.image 为 setImage(_:for:) 的封装
    func time3() -> Void {
        timer.map({
            let name = $0%2 == 0 ? "delete_btn" : "delete_cell"
            return UIImage(named: name)!
        }).bind(to: button.rx.image()).disposed(by: dispose)
        
    }
    
    // MARK: 按钮是否可用（isEnabled）的绑定
    func buttonIsEnabled() -> Void {
        switch1.rx.isOn
            .bind(to: button.rx.isEnabled).disposed(by: dispose)
        switch1.rx.isOn.bind(to: button2.rx.isEnabled).disposed(by: dispose)
        switch1.rx.isOn.bind(to: button3.rx.isEnabled).disposed(by: dispose)
    }
    
    // MARK: 按钮是否可用（isSelected）的绑定
    func buttonIsSelected() -> Void {
        //默认选中第一个按钮
        button.isSelected = true;
        //强制解包，避免后面还需要处理可选类型
        let buttons = [button, button2, button3].map{$0!};
        //创建一个可观察序列，它可以发送最后一次点击的按钮（也就是我们需要选中的按钮）
        let selectedButton = Observable.from(buttons.map{
            btn in btn.rx.tap.map{btn}
        }).merge()
        
        //对于每一个按钮都对selectedButton进行订阅，根据它是否是当前选中的按钮绑定isSelected属性
        for button in buttons {
            selectedButton.map{
                $0 == button
                }.bind(to: button.rx.isSelected).disposed(by: dispose)
        }
    }
    
    func formatTimeInterval(time: NSInteger) -> NSMutableAttributedString {
        let string = String(format: "%0.2d:%0.2d:%0.2d", (time/600) % 600, (time/600)%10, time%60)
        let attributedString = NSMutableAttributedString(string: string)
        
        attributedString.addAttributes([NSAttributedStringKey.font:UIFont(name:"HelveticaNeue-Bold", size:16), NSAttributedStringKey.foregroundColor:UIColor.white, NSAttributedStringKey.backgroundColor:UIColor.orange], range: NSMakeRange(0, 5))
        return attributedString;
    }
    
    // MARK: - alert
    func showMessage(_ text: String) {
        UIAlertController().ba_alertController(self, title: title0, message: msg0, buttonTitleArray: buttonTitleArray, buttonTitleColorArray: []) { (index, alertController) in
            print("点我干嘛？index：", index)
        }
    }
    
    // MARK: - setter, getter
    lazy var button:UIButton = {
        var button = UIButton()
        button.backgroundColor = .green
        button.setTitleColor(.white, for: .normal)
        button.setTitleColor(.yellow, for: .selected)
        button.setTitleColor(.lightGray, for: .disabled)
        //        button.rx.tap.subscribe({[weak self] _ in
        //             print("点击了按钮！")
        //            self?.showMessage("点击了按钮！")
        //        }).disposed(by: dispose)
        
        //        button.rx.tap.subscribe(onNext: { [weak self] in
        //            print("点击了按钮！")
        //            self?.showMessage("点击了按钮！")
        //            }, onError: nil, onCompleted: nil, onDisposed: nil).disposed(by: dispose)
        
        self.view.addSubview(button)
        return button
    }()
    
    lazy var button2:UIButton = {
        var button = UIButton()
        button.backgroundColor = .green
        button.setTitle("title", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.setTitleColor(.yellow, for: .selected)
        button.setTitleColor(.lightGray, for: .disabled)
        
        self.view.addSubview(button)
        return button
    }()
    
    lazy var button3:UIButton = {
        var button = UIButton()
        button.backgroundColor = .green
        button.setTitle("title", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.setTitleColor(.yellow, for: .selected)
        button.setTitleColor(.lightGray, for: .disabled)
        
        self.view.addSubview(button)
        return button
    }()
    
    lazy var switch1:UISwitch = {
        var switch1 = UISwitch()
        
        self.view.addSubview(switch1)
        return switch1
    }()

}
